<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\AdminBaseController;
use app\portal\model\PortalPostModel;
use app\portal\service\PostService;
use app\portal\model\PortalCategoryModel;
use think\Db;
use think\Image;
use app\wechat\controller\User;

//留言诉求管理
class AdminMessageController extends AdminBaseController
{

    //列表
    public function index(){
        $id = cmf_get_current_admin_id();
        if ($id != 1) {
            $where['reply_user_id'] = $id;
        }else{
            $where = [];
        }
        $where['delete_time'] = 0;
        $log_list = Db::name('message')
            ->alias('a')
            ->join('cmf_member b','a.user_id=b.id')
            ->join(' cmf_wechat_department_user c','c.user_id=b.openid')
            ->join(' cmf_wechat_department d','d.id=c.department_id')
            ->field('b.id as user_id,a.*,b.user_login,b.mobile,b.openid,c.department_id,d.name')
            ->where($where)
            ->order("a.time desc")
            ->paginate(11);
        $sort = Db::name('message_sort')
            ->column('id,name');
        $this->assign('sort',$sort);

        $admin_user = Db::name('user')
            ->column('id,user_login');
        $this->assign('admin_user',$admin_user);

        
        // 获取分页显示
        $page = $log_list->render();
       
        $this->assign("page", $page);
  
        $this->assign("data", $log_list);
        return $this->fetch();
    }
    //指定回复人员
    public function reply()
    {
        $id = $this->request->param('id',0,'intval');
        $log_list = Db::name('message')
            ->find($id);
        $this->assign('result',$log_list);

        $admin_user = Db::name('role_user')
        ->alias('a')
        ->join('cmf_user b','a.user_id=b.id','RIGHT')
        ->field('b.id,b.user_login')
        ->where('a.role_id',7)
        ->select();
        $this->assign('admin_user',$admin_user);
        return $this->fetch();
    }
    //指定回复人员提交
    public function replyPost()
    {
        $id = $this->request->param('id',0,'intval');
        $user_id = $this->request->param('user_id',0,'intval');
        if (empty($user_id)) {
            $this->error('回复人员必选');
        }
        $res = Db::name('message')->where('id',$id)->update(['reply_user_id'=>$user_id]);
        if ($res) {
            $this->success('选择成功');
        }else{
            $this->error('操作失败');
        }
    }
    //删除提交
    public function delete(){
        $param   = $this->request->param();
        if (isset($param['id'])) {
            $id   = $this->request->param('id', 0, 'intval');
            $data = Db::name('message')->find($id);
            $res = Db::name('message')->where(['id'=>$id])->update(['delete_time'=>time()]);
            if ($res) {
                $data   = [
                    'object_id'   => $data['id'],
                    'create_time' => time(),
                    'table_name'  => 'message',
                    'name'        => $data['content'],
                    'site_id'     => 1,  //站点ID
                ];
                Db::name('recycleBin')->insert($data);
                //操作日志
                admin_log($data['content'], 'delete', '留言诉求');

                $this->success('删除成功!', url('AdminMessage/index'));
            }else{
                $this->error('删除失败');
            }
        }
    }
    //回复
    public function edit()
    {
        return $this->fetch();
    }

    //回复提交
    public function editPost()
    {
        $param   = $this->request->param();
        $id   = $this->request->param('id', 0, 'intval');

        $res = Db::name('message')->where(['id'=>$id])->update(['reply'=>$param['content'],'reply_time'=>time()]);
        $time = Db::name('message')->field('time')->where(['id'=>$id])->value('time');
        if ($res) {
            $info = Db::name('message')
            ->alias('a')
            ->join('cmf_member b','a.user_id=b.id')
            ->where(['a.id'=>$id])
            ->value('b.openid');

            $user = new User();
            $descr = "<div class=\"normal\">温馨提示：您".date('Y-m-d',$time)."提交的留言诉求管理员已回复，具体情况请进入机关事务管理平台应用查看。</div>";
            $url = url('portal/message/indexlist','','html',true);
            $user->send($info,'留言诉求',$descr,$url);
            //操作日志
            admin_log($param['content'], 'edit', '留言诉求回复');
            $this->success('回复成功!', url('AdminMessage/index'));
        }else{
            $this->error('回复失败');
        }
    }
    //统计时间段页面
    public function timeman(){
        
        $log_list = Db::name('message_time')->order('id desc')->select();
  
        $this->assign("data", $log_list);
        return $this->fetch();
    }
    //添加页面
    public function addtime(){
        return $this->fetch();
    }
    //添加提交
    public function addtimePost()
    {   
        
        if ($this->request->isPost()) {
            $post   = $this->request->param();
            
            if (empty($post['time']) || !is_numeric($post['time']) || $post['time'] <0) {
                $this->error("不能为空且必须大于0的数字！");
            }
            $data = Db::name('message_time')->where(['time'=>$post['time']])->find();
            if ($data) {
                $this->error("已存在");
            }
            $res = Db::name('message_time')->insert($post);
            if ($res) {
                //操作日志
                admin_log($post['name'], 'add', '统计时间段');

                $this->success('添加成功!', url('AdminMessage/timeman'));
            }else{
                $this->error('添加失败');
            }
            
        }

    }
    //编辑
    public function edittime(){
        $id = $this->request->param('id', 0, 'intval');
        $data = Db::name('message_time')->find($id);
        $this->assign('result',$data);
        return $this->fetch();
    }
    //编辑提交
    public function edittimePost(){
        if ($this->request->isPost()) {
            $post   = $this->request->param();
            
            if (empty($post['time']) && is_numeric($post['time']) && $post['time'] >0) {
                $this->error("不能为空且必须大于0的数字！");
            }
            $data = Db::name('message_time')->where(['time'=>$post['time']])->find();
            if ($data) {
                $this->error("已存在");
            }
            $res = Db::name('message_time')->where(['id'=>$post['id']])->update($post);
            if ($res) {
                //操作日志
                admin_log($post['name'], 'edit', '统计时间段');

                $this->success('编辑成功!', url('AdminMessage/timeman'));
            }else{
                $this->error('编辑失败');
            }
            
        }
    }
    //删除提交
    public function deletetime(){
        $param   = $this->request->param();
        if (isset($param['id'])) {
            $id   = $this->request->param('id', 0, 'intval');
            $data = Db::name('message_time')->find($id);
            $res = Db::name('message_time')->where(['id'=>$id])->delete();
            if ($res) {
                //操作日志
                admin_log($data['name'], 'delete', '统计时间段');

                $this->success('删除成功!', url('AdminMessage/timeman'));
            }else{
                $this->error('删除失败');
            }
        }
    }
    //回复时间统计    
    public function timecount(){
        $sort = Db::name('message_sort')
        ->order('id')
        ->select()
        ->toArray();
        $countsort = count($sort);
        $sort2 =  Db::name('message_sort')
        ->order('id')->column('id,name');
        $this->assign('sort',$sort2);
        

        $admin_user = Db::name('role_user')
        ->alias('a')
        ->join('cmf_user b','a.user_id=b.id','RIGHT')
        ->field('b.id,b.user_login')
        ->where('a.role_id',7)
        ->order('id')
        ->select()
        ->toArray();
        $countadmin = count($admin_user);
        $admin_user2 = Db::name('role_user')
        ->alias('a')
        ->join('cmf_user b','a.user_id=b.id','RIGHT')
        ->field('b.id,b.user_login')
        ->where('a.role_id',7)
        ->order('id')->column('b.id,b.user_login');
        $this->assign('admin_user',$admin_user2);
        


        $timeman = Db::name('message_time')
        ->order('time')
        ->select()
        ->toArray();
        $this->assign('timeman',$timeman);
        $counttimeman = count($timeman);

        $post = $this->request->param();
        $between_start = strtotime(date('Y-m'));
        $between_end = strtotime('+1 month',strtotime(date('Y-m')))-(60*60*24);
        $where['time']  = ['between',[$between_start,$between_end]];
        $this->assign('between',['start'=>$between_start,'end'=>$between_end]);
        $where['delete_time'] = 0;
        if (!empty($post['sort_id'])) {
            $where['type'] = $post['sort_id'];
        }
        if (!empty($post['admin_user'])) {
            $where['reply_user_id'] = $post['admin_user'];
        }
        if ( !empty($post['start_time']) && !empty($post['end_time'])) {
            $end = strtotime($post['end_time']);
            $start =  strtotime($post['start_time']);
            $where['time']  = ['between',[$start,$end]];
        }

        $data = Db::name('message')
        ->where($where)
        ->field('id,type,time,reply_time,reply_user_id')
        ->select()
        ->toArray();
        $count = count($data);
        
        $num = $num2 = 0;

        $data_type = [];
        for ($j=0; $j < $countsort; $j++) {
            for ($k=0; $k < $countadmin; $k++) { 
                $num += 1;
                $data_type[$num] = ['type'=>$sort[$j]['id'],'reply_user_id'=>$admin_user[$k]['id'],'count'=>0,'noreply'=>0,'else'=>0];
                for ($o=0; $o< $counttimeman; $o++) {
                    $data_type[$num][$timeman[$o]['time']] = 0;
                }
                
                for ($i=0; $i < $count; $i++) { 
                    if ($data[$i]['type'] == $sort[$j]['id']) {
                        if ($admin_user[$k]['id'] == $data[$i]['reply_user_id']) {
                            
                            if (empty($data[$i]['reply_time'])) {
                                $data_type[$num]['noreply'] += 1;
                            }else{
                                $time = ceil(($data[$i]['reply_time']-$data[$i]['time'])/(60*60));
                                $data_type[$num]['time2'][] = $time;
                                if ($timeman[$counttimeman-1]['time'] < $time) {
                                    $data_type[$num]['else'] += 1;
                                }
                                if ($timeman[0]['time'] >= $time) {
                                    $data_type[$num][$timeman[0]['time']] += 1;
                                }
                                for ($d=0; $d < $counttimeman; $d++) {
                                    if ($timeman[$d]['time'] < $time && $timeman[$d+1]['time'] > $time) {
                                        $data_type[$num][$timeman[$d+1]['time']] += 1;
                                    }
                                }
                            }
                            $data_type[$num]['count'] += 1;
                        }
                    }
                }
            }
        }   
        $this->assign('data',$data_type);
        return $this->fetch();
    }
    public function export()
    {
        $sort = Db::name('message_sort')
        ->order('id')
        ->select()
        ->toArray();
        $countsort = count($sort);
        $sort2 =  Db::name('message_sort')
        ->order('id')->column('id,name');
        

        $admin_user = Db::name('role_user')
        ->alias('a')
        ->join('cmf_user b','a.user_id=b.id','RIGHT')
        ->field('b.id,b.user_login')
        ->where('a.role_id',7)
        ->order('id')
        ->select()
        ->toArray();
        $countadmin = count($admin_user);
        $admin_user2 = Db::name('role_user')
        ->alias('a')
        ->join('cmf_user b','a.user_id=b.id','RIGHT')
        ->field('b.id,b.user_login')
        ->where('a.role_id',7)
        ->order('id')->column('b.id,b.user_login');
        


        $timeman = Db::name('message_time')
        ->order('time')
        ->select()
        ->toArray();

        $counttimeman = count($timeman);

        $post = $this->request->param();
        $where['time']  = ['between',[strtotime(date('Y-m')),strtotime('+1 month',strtotime(date('Y-m')))]];
        $where['delete_time'] = 0;
        if (!empty($post['sort_id'])) {
            $where['type'] = $post['sort_id'];
        }
        if (!empty($post['admin_user'])) {
            $where['reply_user_id'] = $post['admin_user'];
        }
        if ( !empty($post['start_time']) && !empty($post['end_time'])) {
            $end = strtotime($post['end_time']);
            $start =  strtotime($post['start_time']);
            $where['time']  = ['between',[$start,$end]];
        }

        $data = Db::name('message')
        ->where($where)
        ->field('id,type,time,reply_time,reply_user_id')
        ->select()
        ->toArray();
        $count = count($data);
        
        $num = $num2 = 0;

        $data_type = [];
        for ($j=0; $j < $countsort; $j++) {
            for ($k=0; $k < $countadmin; $k++) { 
                $num += 1;
                $data_type[$num] = ['type'=>$sort[$j]['id'],'reply_user_id'=>$admin_user[$k]['id'],'count'=>0,'noreply'=>0,'else'=>0];
                for ($o=0; $o< $counttimeman; $o++) {
                    $data_type[$num][$timeman[$o]['time']] = 0;
                }
                
                for ($i=0; $i < $count; $i++) { 
                    if ($data[$i]['type'] == $sort[$j]['id']) {
                        if ($admin_user[$k]['id'] == $data[$i]['reply_user_id']) {
                            
                            if (empty($data[$i]['reply_time'])) {
                                $data_type[$num]['noreply'] += 1;
                            }else{
                                $time = ceil(($data[$i]['reply_time']-$data[$i]['time'])/(60*60));
                                $data_type[$num]['time2'][] = $time;
                                if ($timeman[$counttimeman-1]['time'] < $time) {
                                    $data_type[$num]['else'] += 1;
                                }
                                if ($timeman[0]['time'] >= $time) {
                                    $data_type[$num][$timeman[0]['time']] += 1;
                                }
                                for ($d=0; $d < $counttimeman; $d++) {
                                    if ($timeman[$d]['time'] < $time && $timeman[$d+1]['time'] > $time) {
                                        $data_type[$num][$timeman[$d+1]['time']] += 1;
                                    }
                                }
                            }
                            $data_type[$num]['count'] += 1;
                        }
                    }
                }
            }
        }   
        
        
        
        $str = '类型,回复人员,';
        foreach ($timeman as $key => $value) {
            $str.=$value['time']."小时,";
        }
        $str .= "其他时间,未回复"."\n";
        $str = iconv('utf-8','gb2312//TRANSLIT',$str);
        //操作日志
        admin_log('', '', '导出留言回复统计');
        for ($i=1,$counts=count($data_type); $i <= $counts; $i++) { 
            if($data_type[$i]['count'] == 0){
                unset($data_type[$i]);
            }else{
                $csv[] = iconv('utf-8','gb2312//TRANSLIT',$sort2[$data_type[$i]['type']]);
                $csv[] = iconv('utf-8','gb2312//TRANSLIT',$admin_user2[$data_type[$i]['reply_user_id']]);
                foreach ($timeman as $key => $value) {
                    $time = round($data_type[$i][$value['time']]/$data_type[$i]['count'],2)*100;
                    $csv[] = iconv('utf-8','gb2312//TRANSLIT',$time."%");
                }
                $time2 = round($data_type[$i]['else']/$data_type[$i]['count'],2)*100;
                $time3 = round($data_type[$i]['noreply']/$data_type[$i]['count'],2)*100;
                $csv[] = iconv('utf-8','gb2312//TRANSLIT',$time2."%");
                $csv[] = iconv('utf-8','gb2312//TRANSLIT',$time3."%");
                $string .= implode(",",$csv)."\n";
            }
        }
        $filename = "留言回复统计_".date('YmdHis').'.csv'; //设置文件名
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str.$string; 
    }
}
